/*
 * job_generator.cpp
 *
 *  Created on: 2009-1-7
 *      Author: fanliangliang
 */

#include "job_generator.h"
#include "common_struct.h"
#include "compressor.h"
#include "time_set.h"

using namespace toxic;

JobGenerator::JobGenerator(Compressor* compressor, const vector<Item*>* items)
:compressor_(compressor)
,items_(items)
,isRunning_(true) {

}

JobGenerator::~JobGenerator() {

}

void JobGenerator::run() {
	int previousMinute = -1;
	while (isRunning_) {
		Time currentTime;
		// a little optimize here, check the items_ only if the minutes changed
		if (previousMinute != currentTime.minute) {
			previousMinute = currentTime.minute;
			if (JobArgument* job = getJobByTime(currentTime)) {
				// notify compressor
				compressor_->push(job);
			}
		}
		Thread::sleep(1000);
	}
}

void JobGenerator::stop() {
	isRunning_ = false;
}

JobArgument* JobGenerator::getJobByTime(const Time& time) const {
	JobArgument* job = 0;
	foreach (Item* item, *items_) {
		if (item->timeset->contain(time)) {
			if (job == 0) {
				job = new JobArgument();
				job->time = new Time(time);
			}
			foreach (Action* action, item->actions) {
				job->actions.push_back(new Action(*action));
			}
		}
	}
	return job;
}
